package activities;

import helper.ExercisesEnum;
import helper.Exercise;
import helper.GraphDataWrapper;
import helper.Settings;
import helper.TimeSpan;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.Set;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.example.intellifit.R;

public class StatisticsActivity extends Activity implements OnGestureListener, AnimationListener {

	private static final int SWIPE_MIN_DISTANCE = 100;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 300;

	private GestureDetector gDetector;

	private ViewState currentViewState = ViewState.Day;
	private TimeSpan currentTimeSpan;

	private ExercisesEnum[] selectedExcercises = new ExercisesEnum[] { ExercisesEnum.BICEP_CURLS,
			ExercisesEnum.PUSH_UPS, ExercisesEnum.SQUATS, ExercisesEnum.PULL_UPS };

	private Exercise currentExercise;
	ImageButton previousBtn;
	ImageButton nextBtn;
	Button todayBtn;
	Spinner spinner, exTypeSpinner, exSpinner;
	String[] viewSelection;
	Boolean flaegle_first_time = true;
	Boolean flag_coming_from_act = false;
	Settings settings;

	ArrayList<String> exTypeList, exList;
	LinkedHashMap<String, LinkedHashMap<String, Integer>> exercises;

	ArrayAdapter<String> exTypeAdapter, exAdapter;

	public enum ViewState {
		Month, Week, Day, YEAR, MONTH
	}

	private XYMultipleSeriesDataset _repsGrphDataset = new XYMultipleSeriesDataset();
	private XYMultipleSeriesRenderer _repsGrphRenderer = new XYMultipleSeriesRenderer();

	// the actual graphs
	private GraphicalView repetitionsChartView = null;
	private LinearLayout graph1;
	private GraphDataWrapper gdw;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		settings = Settings.getInstance();
		exercises = Settings.getExercises();
		// if this activity was called from the result view in the
		// repetitionsActivity
		// extract the current chosen exercise to be shown
		try {
			Bundle b = getIntent().getExtras();
			Object o = b.get("exercise_data");
			Exercise bla = (Exercise) o;
			currentExercise = Settings.getExerciseId(bla.getName());
			flag_coming_from_act = true;
		} catch (NullPointerException e) {
			currentExercise = Settings.lastExerciseDone;

			flag_coming_from_act = true;
		}
		if (currentExercise.getName() == "Biceps Curls") {
			currentExercise.setGroupName("Weigth");
		} else if (currentExercise.getName() == "Squat") {
			currentExercise.setGroupName("Body Weigth");
		}
		setContentView(R.layout.activity_statistics);
		Calendar c = Calendar.getInstance();

		Log.i("DB-TEST", c.getTime().toString());
		currentTimeSpan = new TimeSpan(currentViewState);

		gDetector = new GestureDetector(this, this);
		gdw = new GraphDataWrapper(this, currentViewState, currentTimeSpan);

		initViewComponents();

		createRepetitionsGraphView();
		flaegle_first_time = true;
		flag_coming_from_act = false;
	}

	private void initViewComponents() {

		spinner = (Spinner) findViewById(R.id.changeViewSpinnerBtn);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.statistics_view_state,
				android.R.layout.simple_spinner_item);

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

				// storing string resources into Array
				viewSelection = getResources().getStringArray(R.array.statistics_view_state);
				updateViewState();

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// do nothing

			}

		});

		exSpinner = (Spinner) findViewById(R.id.changeExSpinnerBtn);
		exList = new ArrayList<String>();
		exAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, exList);
		exSpinner.setAdapter(exAdapter);
		exSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

				String ex = exList.get(position);
				Exercise e = Settings.getExerciseId(ex);
				Integer exId = e.getId();
				currentExercise = new Exercise(exId, ex);
				createRepetitionsGraphView();

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// do nothing

			}

		});

		exTypeSpinner = (Spinner) findViewById(R.id.changeExTypeSpinnerBtn);
		exTypeList = new ArrayList<String>(exercises.keySet());
		exTypeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, exTypeList);
		exTypeSpinner.setAdapter(exTypeAdapter);

		exTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				String exType = exTypeList.get(position);

				Set<String> exTypeSet = exercises.get(exType).keySet();

				exList.clear();
				exList.addAll(exTypeSet);
				exAdapter.notifyDataSetChanged();
				if (!flaegle_first_time) {
					exSpinner.performClick();
				} else {
					flaegle_first_time = !flaegle_first_time;
				}
			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// do nothing

			}

		});

		if (flag_coming_from_act) {
			int one = exTypeAdapter.getPosition(currentExercise.getGroupName());
			exTypeSpinner.setSelection(one);
			// exTypeSpinner.performClick();
			String exType = exTypeList.get(one);

			Set<String> exTypeSet = exercises.get(exType).keySet();

			exList.clear();
			exList.addAll(exTypeSet);
			exAdapter.notifyDataSetChanged();

			int two = exAdapter.getPosition(currentExercise.getName());
			exSpinner.setSelection(two);

		}

		previousBtn = (ImageButton) findViewById(R.id.previousBtn);
		nextBtn = (ImageButton) findViewById(R.id.nextBtn);
		todayBtn = (Button) findViewById(R.id.todayBtn);
		todayBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				currentTimeSpan = new TimeSpan(currentViewState);
				createRepetitionsGraphView();
			}
		});

	}

	public void updateViewState() {
		int pos = spinner.getSelectedItemPosition();
		if (viewSelection[pos].toLowerCase().equals("year")) {
			this.currentViewState = ViewState.Month;
		} else if (viewSelection[pos].toLowerCase().equals("week")) {
			this.currentViewState = ViewState.Day;
		}

		createRepetitionsGraphView();
	}

	public void updateExercisesWhenTypeChanged() {
		int pos = exTypeSpinner.getSelectedItemPosition();
	}

	public void createRepetitionsGraphView() {

		this.graph1 = (LinearLayout) findViewById(R.id.chart);

		graph1.removeAllViews();

		// this._repsGrphDataset = GraphDataProvider.updateRepetitionsDataset(
		// _repsGrphDataset, selectedExcercises, currentViewState,
		// currentTimeSpan);

		gdw.updateSingleDataset(currentExercise.getId(), 1, currentViewState, currentTimeSpan,
				currentExercise.getName());
		gdw.updateSingleRendererStyling();

		repetitionsChartView = ChartFactory.getBarChartView(getApplicationContext(), gdw.getDataset(),
				gdw.getRenderer(), org.achartengine.chart.BarChart.Type.DEFAULT);

		graph1.addView(repetitionsChartView, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

	}

	/**
	 * Update the timespan. Depending on the parameter it is either decreased or
	 * increased
	 * 
	 * @param b
	 */
	public void updateTimeSpan(boolean b) {
		if (b) {
			currentTimeSpan.increaseTimeSpan(currentViewState);
		} else {
			currentTimeSpan.decreaseTimeSpan(this.currentViewState);
		}
	}

	public void updateRepetitionsChartView() {

		repetitionsChartView.repaint();

	}

	@Override
	public boolean onDown(MotionEvent e) {

		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
			return false;

		// right to left swipe
		if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			Log.i("SWIPE_DET", "RIGHT-->LEFT");
			TranslateAnimation animate = new TranslateAnimation(0, -graph1.getWidth(), 0, 0);
			animate.setDuration(500);
			animate.setAnimationListener(this);

			// repetitionsChartView = null;
			// updateTimeSpan(true);
			// _repsGrphDataset = new XYMultipleSeriesDataset();
			// _repsGrphRenderer = new XYMultipleSeriesRenderer();
			this.currentTimeSpan.increaseTimeSpan(currentViewState);
			graph1.startAnimation(animate);
			((Button) findViewById(R.id.todayBtn)).startAnimation(animate);
			repetitionsChartView = null;

		} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
			Log.i("SWIPE_DET", "LEFT->RIGHT");
			TranslateAnimation animate = new TranslateAnimation(0, graph1.getWidth(), 0, 0);
			animate.setDuration(500);
			animate.setAnimationListener(this);
			// animate.setFillAfter(true);
			this.currentTimeSpan.decreaseTimeSpan(currentViewState);
			graph1.startAnimation(animate);
			((Button) findViewById(R.id.todayBtn)).startAnimation(animate);
			repetitionsChartView = null;

		}

		return true;
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {

		return false;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {

		return false;
	}

	// @Override
	// public boolean onTouchEvent(MotionEvent event) {
	//
	// return gDetector.onTouchEvent(event);
	// }

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {

		super.dispatchTouchEvent(ev);
		return gDetector.onTouchEvent(ev);
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		createRepetitionsGraphView();

	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}

	@Override
	public void onAnimationStart(Animation animation) {

	}
}
